<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace console\logics;

use common\CacheKey;
use common\Common;
use common\models\ProductCateModel;

class ProductLogic extends BaseLogic
{
    public static function setCategory(): bool
    {
        $redis = \Yii::$app->redis;
        $cate = [];
        $models = ProductCateModel::find()->where(['status' => 1])->orderBy(['pid' => SORT_DESC, 'id' => SORT_DESC])->all();
        foreach ($models as $model) {
            if (! $model instanceof ProductCateModel || ! $model->id) {
                continue;
            }
            $key = Common::spaceToLines($model->name);
            $redis->hmset(CacheKey::PRODUCT_CATE_HASH, $key, $model->id);
            $cate[$model->id][] = $model->id;
            if ($model->pid) {
                $cate[$model->pid] = array_merge($cate[$model->pid] ?? [], $cate[$model->id]);
            }
            $cate[$model->id] = array_unique($cate[$model->id]);
        }
        foreach ($cate as $cateId => $cateIds) {
            $redis->hmset(CacheKey::PRODUCT_CATE_IDS_HASH, $cateId, implode(',', $cateIds));
        }

        return true;
    }
}
